package com.jd.fruit.controller.admin.auth;

import java.io.IOException;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.jd.fruit.common.annotation.Controller;
import com.jd.fruit.common.controller.BaseController;
import com.jd.fruit.common.util.DictUtil;
import com.jd.fruit.common.util.StringUtil;
import com.jd.fruit.model.admin.auth.AdminUserRole;
import com.jd.fruit.model.admin.auth.Menu;
import com.jd.fruit.model.admin.auth.Role;
import com.jd.fruit.model.admin.auth.RoleMenu;
import com.jfinal.kit.StrKit;

/**
 * 角色管理
 * 
 * @author lishunfeng
 * 
 */
@Controller("/admin/auth/role")
public class RoleController extends BaseController {
	/**
	 * 添加菜单
	 */
	public void add() {
		this.getRequest().setAttribute("oprtype", DictUtil.oprSave);
		render("role_add.html");
	}

	/**
	 *角色数据列表
	 */
	public void list() {
		Role role = Role.dao;
		List<Role> list = role.list();
		this.getRequest().setAttribute("list", list);
		render("role_list.html");
	}

	/**
	 * 编辑角色
	 */
	public void detail() {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		Role role = Role.dao.findById(id);
		this.setAttr("role", role);
		this.setAttr("oprtype", DictUtil.oprUpdate);
		render("role_add.html");// 这个是页面的命名规范
	}

	/**
	 * 删除角色
	 * 
	 * @throws IOException
	 */
	public void delete() throws IOException {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		boolean isOk = Role.dao.deleteById(id);
		if (isOk) {// 删除成功
			//删除管理员与角色关联数据
		      AdminUserRole.dao.delAdminRelationRole("role_id",id);
			//删除角色关联菜单数据
			RoleMenu.dao.delRloeRelationMenu(id);
			this.renderText(DictUtil.success);
		} else { // 删除失败
			this.renderText(DictUtil.failed);
		}
	}

	/**
	 *保存角色
	 */
	public void save() {
		String oprtyp = this.getPara("oprtype");
		String rolename=this.getPara("rolename");
		String description=this.getPara("description");
		String menueids=this.getPara("menueids");
		String updateRoleid=this.getPara("roleid");
		RoleMenu roleMenu=this.getModel(RoleMenu.class);
		Role role = getModel(Role.class);
		role.set("name", rolename);
		role.set("description", description);
		if (oprtyp.equals(DictUtil.oprSave)) {
		    String newRoleid=Role.dao.save(role);
			//保存角色对应权限
		   roleMenu.set("role_id", newRoleid);
	       RoleMenu.dao.save(roleMenu,menueids);
		} else if(updateRoleid!=null){
			//保存角色
			role.set("id", updateRoleid);
			role.update();
			//保存角色对应的菜单
			roleMenu.set("role_id", updateRoleid);
			RoleMenu.dao.save(roleMenu,menueids);
		}
		this.renderText(DictUtil.success);
	}

	/**
	 * 加载菜单Jason数据
	 * 
	 * @throws IOException
	 */
	public void loadMenuData() {
		String type = getPara("type");
		String result = "";
		String detailId=this.getPara("roleid");
		String roleMap=RoleMenu.dao.roleMap(detailId);
		JSONArray jsarray = null;
		if (!StrKit.isBlank(type)) {
			jsarray = Menu.dao.loadTree(roleMap);
			if (jsarray != null) {
				result = jsarray.toJSONString();
			}
		}
		renderJson(result);
	}
	


}
